package com.hoshiicloud.user.controller.store;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.auth.vo.TokenUsersVO;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.user.entity.store.StoreDepartment;
import com.hoshiicloud.user.param.store.StoreDepartmentAddParam;
import com.hoshiicloud.user.param.store.StoreDepartmentQueryParam;
import com.hoshiicloud.user.param.store.StoreDepartmentUpdateParam;
import com.hoshiicloud.user.param.store.StoreUsersQueryParam;
import com.hoshiicloud.user.service.IStoreManageService;
import com.hoshiicloud.user.service.impl.StoreManageServiceImpl;
import com.hoshiicloud.user.service.store.StoreDepartmentService;
import com.hoshiicloud.user.service.store.StoreUsersService;
import com.hoshiicloud.user.utils.UserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.hoshiicloud.user.service.IStoreManageService;

/**
 * <p>
 * 店铺部门 控制器
 * </p>
 *
 * @author campchen
 * @since 2019-07-24
 */
@Slf4j
@RestController
@RequestMapping("/store/storeDepartment")
@Api(value = "店铺部门", tags = {"店铺部门"})
@ApiSort(43)
public class StoreDepartmentController {
    @Autowired
    private StoreDepartmentService storeDepartmentService;

    @Autowired
    private StoreUsersService storeUsersService;

    @Autowired
    private IStoreManageService iStoreManageService;


    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 分页查询店铺部门
     */
    @ApiOperation(value = "分页查询店铺部门")
    @PostMapping("/getPage")
    public Response page(@RequestBody StoreDepartmentQueryParam param) {
        try {
            QueryWrapper<StoreDepartment> queryWrapper = new QueryWrapper<StoreDepartment>();
            queryWrapper.lambda()
                    .eq((param.getStoreId() != null), StoreDepartment::getStoreId, param.getStoreId())
                    .eq((param.getParentId() != null), StoreDepartment::getParentId, param.getParentId())
                    .eq(StringUtils.isNotBlank(param.getName()), StoreDepartment::getName, param.getName())
                    .eq(StringUtils.isNotBlank(param.getOpenPermit()), StoreDepartment::getOpenPermit, param.getOpenPermit())
                    .eq(StringUtils.isNotBlank(param.getCharge()), StoreDepartment::getCharge, param.getCharge())
                    .eq(StringUtils.isNotBlank(param.getIdCard()), StoreDepartment::getIdCard, param.getIdCard())
                    .eq(StringUtils.isNotBlank(param.getBankNumber()), StoreDepartment::getBankNumber, param.getBankNumber())
                    .eq(StringUtils.isNotBlank(param.getBankName()), StoreDepartment::getBankName, param.getBankName())
                    .eq(StringUtils.isNotBlank(param.getBankAddress()), StoreDepartment::getBankAddress, param.getBankAddress())
                    .eq(StringUtils.isNotBlank(param.getTaxation()), StoreDepartment::getTaxation, param.getTaxation())
                    .eq(StringUtils.isNotBlank(param.getPiaohao()), StoreDepartment::getPiaohao, param.getPiaohao())
                    .eq(StringUtils.isNotBlank(param.getTelphone()), StoreDepartment::getTelphone, param.getTelphone())
                    .eq(StringUtils.isNotBlank(param.getMobile()), StoreDepartment::getMobile, param.getMobile())
                    .eq(StringUtils.isNotBlank(param.getFax()), StoreDepartment::getFax, param.getFax())
                    .eq(StringUtils.isNotBlank(param.getHome()), StoreDepartment::getHome, param.getHome())
                    .eq(StringUtils.isNotBlank(param.getEmail()), StoreDepartment::getEmail, param.getEmail())
                    .eq(StringUtils.isNotBlank(param.getAddress()), StoreDepartment::getAddress, param.getAddress());
            IPage<StoreDepartment> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            return Response.data(storeDepartmentService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询店铺部门异常", e);
            return Response.failed("分页查询店铺部门异常");
        }

    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据id查询店铺部门
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询店铺部门")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response<StoreDepartment> queryById(@PathVariable("id") Long id) {
        return Response.data(storeDepartmentService.getById(id));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增店铺部门")
    public Response saveStoreDepartment(@RequestBody @Valid StoreDepartmentAddParam param, HttpServletRequest request) {
        StoreDepartment entity;
        TokenUsersVO user = UserInfoUtil.getUserInfo(request);
        if(user.getStoreId()!=null && !user.getStoreId().equals("")){
            param.setStoreId(user.getStoreId());
        }
        try {
            entity = BeanUtils.covertType(param, StoreDepartment.class);
        } catch (Exception e) {
            log.error("新增店铺部门Bean转换异常", e);
            return Response.failed("新增店铺部门Bean转换异常");
        }
        return Response.data(storeDepartmentService.save(entity));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改店铺部门
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改店铺部门")
    public Response updateStoreDepartmentById(@RequestBody @Valid StoreDepartmentUpdateParam param) {
        StoreDepartment entity;
        try {
            entity = BeanUtils.covertType(param, StoreDepartment.class);
        } catch (Exception e) {
            log.error("修改店铺部门Bean转换异常", e);
            return Response.failed("新增店铺部门Bean转换异常");
        }
        return Response.data(storeDepartmentService.updateById(entity));
    }


    /**
     * 根据条件查询店铺部门
     * @param request
     * @return
     */
    @ApiOperation(value = "根据名称查询店铺部门名称和员工姓名")
    @PostMapping("/getStoreDeptNameAndStoreUserName")
    public Response getStoreDeptNameAndStoreUserName(@RequestBody StoreDepartmentQueryParam param,HttpServletRequest request) {
        TokenUsersVO user = UserInfoUtil.getUserInfo(request);
        if(param==null){
            return Response.failed("param为空");
        }
        if(user.getStoreId()!=null && !user.getStoreId().equals("")){
            param.setStoreId(user.getStoreId());
        }else{
            return Response.failed("店铺id为空");
        }
        System.out.println(param.getQueryName()+"/////param.getQueryName()");
        if(param.getQueryName().equals("")){
            return Response.failed("查询名称为空");
        }
        System.out.println(user.getStoreId()+"/////+user.getStoreId()");

        List<Map> storeDeptNamelist = storeDepartmentService.storeDeptNameList(param);
        StoreUsersQueryParam suqParam = new StoreUsersQueryParam();
        suqParam.setStoreId(param.getStoreId());
        suqParam.setQueryName(param.getQueryName());
        List<Map> storeUserNamelist = storeUsersService.storeUserNameList(suqParam);
        List returnList=new ArrayList();
        returnList.addAll(storeDeptNamelist);
        returnList.addAll(storeUserNamelist);
        return Response.data(returnList);
    }

    @ApiOperation(value = "根据id集合查询店铺部门")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("获取店铺部门id集合失败");
        }
        ids.sort(null);
        return Response.data(storeDepartmentService.getByIds(ids, StringUtils.join(ids, "")));
    }

    /**
     * 根据条件查询店铺部门
     * @param request
     * @return
     */
    @ApiOperation(value = "根据条件查询店铺部门")
    @GetMapping("/getStoreDepartment")
    public Response getStoreDepartment(@RequestBody (required = false) StoreDepartmentQueryParam param,HttpServletRequest request) {
        TokenUsersVO user = UserInfoUtil.getUserInfo(request);
        if(param==null){
            param = new StoreDepartmentQueryParam();
        }
        if(user.getStoreId()!=null && !user.getStoreId().equals("")){
            param.setStoreId(user.getStoreId());
        }else{
            return Response.failed("店铺id为空");
        }

        List<Map> storeDeptlist = storeDepartmentService.storeDeptList(param);
        JSONArray deptResult = iStoreManageService.listToTree(JSONArray.parseArray(JSON.toJSONString(storeDeptlist)),"id","parent_id","children");
        Map addMap = new HashMap<>();
        addMap.put("storeDeptlist",deptResult);
        return Response.data(addMap);
    }


}
